using System;
using FluentValidation.Attributes;
using FluentValidation.Internal;
using FluentValidation.Resources;
using FluentValidation.Results;

namespace FluentValidation.Validators
{
    [ValidationMessage(Key = DefaultResourceManager.InclusiveBetweenValidator)]
    public class InclusiveBetweenValidator<TInstance, TType> : IPropertyValidator<TInstance, TType>, IBetweenValidator<TType>  where TType : IComparable<TType> 
    {
        public InclusiveBetweenValidator(TType from, TType to)
        {
            To = to;
            From = from;

            if (to.CompareTo(from) == -1)
            {
                throw new ArgumentOutOfRangeException("to", "To should be larger than from.");
            }
        }

        #region IBetweenValidator Members
        public TType From { get; private set; }
        public TType To { get; private set; }
        #endregion

        #region IPropertyValidator<TInstance,string> Members
        public PropertyValidatorResult Validate(PropertyValidatorContext<TInstance, TType> context)
        {
            if (context.PropertyValue.CompareTo(From) < 0 || context.PropertyValue.CompareTo(To) > 0)
            {
                MessageFormatter formatter = new MessageFormatter()
                    .AppendProperyName(context.PropertyDescription)
                    .AppendArgument("From", From)
                    .AppendArgument("To", To)
                    .AppendArgument("Value", context.PropertyValue);

                string error = context.GetFormattedErrorMessage(GetType(), formatter);

                return PropertyValidatorResult.Failure(error);
            }
            return PropertyValidatorResult.Success();
        }
        #endregion
    }

    public interface IBetweenValidator<T> : IPropertyValidator
    {
        T From { get; }
        T To { get; }
    }
}